/*
 * CRtpPackager.cpp
 *
 *  Created on: 2015年7月5日
 *      Author: terry
 */

#include "CRtpPackager.h"


namespace av
{

CRtpPackager::CRtpPackager(int type, MediaCodec codec):
		m_type(type),
		m_codec(codec)
{
}

CRtpPackager::~CRtpPackager()
{
}

void CRtpPackager::slice(const MediaPacket& pkt, int maxSize, RtpPackagerSink* pSink)
{
	if (!pSink)
	{
		return;
	}

	if (pkt.size <= maxSize)
	{
		RtpPacket pktOut;
		pktOut.data = pkt.data;
		pktOut.size = pkt.size;
		pktOut.ts = (uint32_t)pkt.pts;

		pktOut.mark = true;
		pktOut.pt = m_payload;

		pSink->onSlicePacket(pktOut);
	}
	else
	{
		RtpPacket pktOut;
		pktOut.ts = (uint32_t)pkt.pts;
		pktOut.pt = m_payload;

		uint8_t* p = pkt.data;
		int leftSize = pkt.size;
		while (leftSize > maxSize)
		{
			pktOut.data = p;
			pktOut.size = maxSize;
			pktOut.mark = false;

			p += maxSize;
			leftSize -= maxSize;

			pSink->onSlicePacket(pktOut);
		}

		pktOut.data = p;
		pktOut.size = leftSize;
		pktOut.mark = true;
		pSink->onSlicePacket(pktOut);

	}
}

bool CRtpPackager::join(const RtpPacket& pktIn, MediaPacket& pktOut)
{
	bool found = false;

	ByteBuffer& buffer = m_buffer.getCurBuffer();
	buffer.write(pktIn.data, pktIn.size);

	if (pktIn.mark)
	{
		pktOut.type = m_type;
		pktOut.pts = pktIn.ts;
		pktOut.duration = 0;
		pktOut.write(buffer.data(), buffer.size());

		m_buffer.switchBuffer();
		m_buffer.getCurBuffer().clear();

		found = true;
	}
	return found;
}

void CRtpPackager::reset()
{
    m_buffer.clear();
}

bool CRtpPackager::getFormat(MediaFormat& fmt)
{
	if (m_type == MEDIA_TYPE_VIDEO)
	{
		fmt.m_codec = m_codec;
	}
	else
	{
		fmt.m_audioCodec = m_codec;
	}
	
	return true;
}


} /* namespace av */
